package cn.xiaobai.v2;

import cn.xiaobai.http.ResponseHeader;
import cn.xiaobai.utils.LoggerFactory;

import java.io.*;
import java.net.Socket;
import java.nio.charset.StandardCharsets;

/**
 * @Author yangdaji
 * @Date 2023/11/29
 * @PackageName cn.xiaobai.v2
 * @ClassName HttpHandler
 */
public class HttpHandler2 implements Runnable {

    static LoggerFactory.Logger log = LoggerFactory.getLogger(HttpHandler2.class);

    private String body;

    private Socket socket = null;

    public HttpHandler2(Socket socket) {
        this.socket = socket;
    }

    public void setBody(String body) {
        this.body = body;
    }

    @Override
    public void run() {
        try {
            // 1. 使用线程处理请求
            log.info("====== tomcat v2 监听 {} 端口, 当前线程名称: {}", socket.getPort(), Thread.currentThread().getName());

            // 接收到发送的数据
            InputStream inputStream = socket.getInputStream();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));

            // 2.读取数据
            String msg = "";
            log.info("开始接收数据");
            while ((msg = bufferedReader.readLine()) != null) {
                if (msg.length() == 0) {
                    break;
                }
                log.info("接收到客户端请求数据: {}", msg);
            }

            log.info("响应客户端数据");
            // 3. 响应数据
            OutputStream outputStream = socket.getOutputStream();
            // 构建响应体, 返回给客户端
            // 响应头
//            String respHeader = "HTTP/1.1 200 OK\r\n" +
//                    "Content-Type: text/html;charset=utf-8\r\n\r\n";

            ResponseHeader responseHeader = new ResponseHeader(200);
            log.info("请求头信息: {}", responseHeader);

            String response = responseHeader + body;
            outputStream.write(response.getBytes());
            // 关闭资源
            outputStream.flush();
            outputStream.close();
            inputStream.close();


        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
